package com.hp.note;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import com.hp.note.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.view.MenuCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;

public class HPNoteEdit extends Activity implements TextToSpeech.OnInitListener{
	private static final String TAG = "HPNoteEdit";
	private TextToSpeech tts;
	private Note note = null;
	private static final int CAMERA_REQUEST = 1888;
	private ImageView imageView;
	private XMLGettersSetters data;

	@SuppressLint("NewApi")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate");
		
		Toast.makeText(getApplicationContext(),"waiting for GPS!", Toast.LENGTH_SHORT).show();
        LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        LocationListener locListener = new MyLocationListener();
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
//~Text to speech--------------------------------------------------------------
		tts = new TextToSpeech(this, this);
        
//~----------------------------------------------------------------------------     
//		// Hiển thị nút back về home
//		getActionBar().setDisplayHomeAsUpEnabled(true);
		setContentView(R.layout.edit);
		note = (Note) getLastNonConfigurationInstance();
		_processIntent();
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		// return super.onRetainNonConfigurationInstance();
		return note;
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.d(TAG, "onNewIntent");
		setIntent(intent);
		_processIntent();
		super.onNewIntent(intent);
	}

	@Override
	protected void onPause() {
		saveNote();
		super.onPause();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.note_context, menu);
		MenuCompat.setShowAsAction(menu.findItem(R.id.saveNote), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.deleteNote), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.shareNote), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.addRecord), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.capture), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.beamData), 1);
		MenuCompat.setShowAsAction(menu.findItem(R.id.text_2_speech), 1);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.text_2_speech:
			speakIt();
			break;
		case R.id.beamData:
			beamData();
			break;
		case R.id.addRecord:
			addRecord();
			break;
		case R.id.deleteNote:
			deleteNote();
			break;
		case R.id.shareNote:
			shareNote();
			break;
		case R.id.capture:
			captureIMG();
			break;
		default:
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void captureIMG() {
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
        	this.imageView = (ImageView)this.findViewById(R.id.imageView1);
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);

            try {
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            	String currentDateandTime = sdf.format(new Date());
            	
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                photo.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
                byte[] b = baos.toByteArray();
                OutputStream is = openFileOutput(currentDateandTime+".jpg",0);
                try {
                    is.write(b);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
	
	public String getWeather(double lat, double lng){
		String weatherstr = "";
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxP;
		try {
			saxP = saxPF.newSAXParser();

			XMLReader xmlR = saxP.getXMLReader();

			
			URL url = new URL("http://www.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query="+lat+","+lng);
			XMLHandler myXMLHandler = new XMLHandler();
			xmlR.setContentHandler(myXMLHandler);
			xmlR.parse(new InputSource(url.openStream()));
			data = XMLHandler.data;
			weatherstr += data.getNamecity();
			weatherstr += data.getTempC() + "°C ";
			weatherstr += data.getCondition();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return weatherstr;
	}

	
	public class MyLocationListener implements LocationListener
    {
        @Override
        public void onLocationChanged(Location loc)
        {
            loc.getLatitude();
            loc.getLongitude();
            String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
            Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
//            String addr = getAddress(loc.getLatitude(), loc.getLongitude());
//            Toast.makeText( getApplicationContext(), addr, Toast.LENGTH_SHORT).show();
            TextView txt = (TextView) findViewById(R.id.txt_locwea);
            String text = getWeather(loc.getLatitude(), loc.getLongitude());
            txt.setText(text);
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
        }
    }
	
	// Gửi dữ liệu đến NoteMapper
	private void _processIntent() {
		EditText textView1 = (EditText) findViewById(R.id.noteTitle);
		EditText textView = (EditText) findViewById(R.id.noteText);
		NoteMapper nm = ((HPNoteApp) getApplication()).getNoteMapper();
		// getIntent().hasExtra("uid");

		Intent intent = getIntent();
		String action = intent.getAction();
		String content = "";
		String noteTitle = "";

		if (action != null && action.equals(android.content.Intent.ACTION_SEND)) {
//			String noteTilte = intent
//					.getStringExtra(android.content.Intent.EXTRA_TEXT);
			String title = intent
					.getStringExtra(android.content.Intent.EXTRA_TITLE);
			String text = intent
					.getStringExtra(android.content.Intent.EXTRA_TEXT);
			if (title != null) {
				content += title;
			}
			if (textView != null) {
				content += text;
			}
		} else {
			// action should be openNote
			if (intent.hasExtra("dbid")) {
				long id = intent.getLongExtra("dbid", -1);
				if (id > 0) {
					note = nm.getNote(id);
				}
			} else if (intent.hasExtra("uid")) {
				String uId = intent.getStringExtra("uid");
				if (uId != null) {
					note = nm.getNote(uId);
				}
			}
		}

		if (note != null) {
			textView1.setText(note.getNotetitle());
			textView.setText(note.getContent());
		} else {
			textView.setText(noteTitle);
			textView.setText(content);
		}

	}
	
	private void speakIt(){
		tts.speak(note.getContent(), TextToSpeech.QUEUE_FLUSH, null);
	}
	private void beamData() {
		Intent intent = new Intent(getApplicationContext(),
				BeamData.class);
		startActivity(intent);
		
	}
	private void addRecord() {
		Intent intent = new Intent(getApplicationContext(),
				AudioActivity.class);
		startActivity(intent);
		
	}
	private void deleteNote() {
		saveNote();
		// NoteMapper nm = ((ShareNoteApp) getApplication()).getNoteMapper();
		// Note note = nm.getNote(uid);
		if (note != null) {
			note.delete();
			NoteMapper nm = ((HPNoteApp) getApplication()).getNoteMapper();
			nm.saveNote(note);

			// toast "save note"
			Toast toast = Toast.makeText(getApplicationContext(), "Deleted",
					Toast.LENGTH_SHORT);
			// toast.setText(R.string.noteSaved);
			toast.show();
			Log.v(TAG, "Note deleted");
		}
		// nm.deleteNote(note);
		// note = null;
		finish();
	}

	private void shareNote() {
		saveNote();

		if (note != null) {
			Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
			shareIntent.setType("text/plain");
			shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
					note.getTitle());
			shareIntent.putExtra(android.content.Intent.EXTRA_TEXT,
					note.getContent());

			startActivity(Intent.createChooser(shareIntent,
					getString(R.string.shareNote)));
		} else {
			// toast "save note"
			Toast toast = Toast.makeText(getApplicationContext(),
					"Nothing to share", Toast.LENGTH_SHORT);
			// toast.setText(R.string.noteSaved);
			toast.show();
		}
	}

	public void saveNote() {

		EditText text = (EditText) findViewById(R.id.noteText);
		EditText text1 = (EditText) findViewById(R.id.noteTitle);
		boolean save = false;
		String textTitle = text1.getText().toString();
		String textString = text.getText().toString();
		if (note == null && textString.length() > 0) {
			note = new Note("");
			note.setNotetitle(textTitle);
			note.setContent(textString);
			// Chú thêm vào nhé
			note.setImgUrl("");
			note.setAudioUrl("");
			note.setLocation("");// x.sjfasdf,y.sádfdfs

			save = true;
		} else if (note != null && !textString.equals(note.getContent())) {
			note.setNotetitle(textTitle);
			note.setContent(textString);
			// Chú thêm vào nhé
			note.setImgUrl("");
			note.setAudioUrl("");
			note.setLocation("");// x.sjfasdf,y.sádfdfs
			save = true;
		}

		if (note != null && save) {
			NoteMapper nm = ((HPNoteApp) getApplication()).getNoteMapper();
			nm.saveNote(note);

			// toast "save note"
			Toast toast = Toast.makeText(getApplicationContext(), "Saved",
					Toast.LENGTH_SHORT);
			// toast.setText(R.string.noteSaved);
			toast.show();
			Log.v(TAG, "Note saved");
		} else {
			Log.v(TAG, "Don't need to save the note");
		}
	}

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub

		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.US);
			// tts.setPitch(5); // set pitch level

			// tts.setSpeechRate(2); // set speech speed rate

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "Language is not supported");
			} else {
	
			}

		} else {
			Log.e("TTS", "Initilization Failed");
		}

	}
	
	
}
